package com.kzl;

import HslCommunication.Core.Types.OperateResult;
import HslCommunication.Core.Types.OperateResultExOne;
import HslCommunication.Profinet.Keyence.KeyenceNanoSerialOverTcp;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class YB06_02 {
    //1.先要定义一个读写的工具
    //2.先定义一个启动的方法
    //3.初始化连接的工具
    //4.定时器读取数据
    private static KeyenceNanoSerialOverTcp plc = null;

    public static void strat() {
        plc = new KeyenceNanoSerialOverTcp();
        plc.setIpAddress("127.0.0.1");
        plc.setPort(8501);
        OperateResult connect = plc.ConnectServer();
        if (connect.IsSuccess) {

            read();
        } else {

        }

    }

    private static void read() {
        // 创建一个ScheduledExecutorService，每秒执行一次任务
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
        Runnable task = () -> {
            try {
                OperateResultExOne<Short> resultExOne = plc.ReadInt16("DM100");
                if (resultExOne.IsSuccess) {
                    Short value = resultExOne.Content;
                    System.out.println("Read value: " + value);
                } else {
                    System.out.println("Failed to read: " + resultExOne.Message);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        };
        // 每1秒（1000毫秒）执行一次任务
        scheduler.scheduleAtFixedRate(task, 0, 10, TimeUnit.SECONDS);
    }
}
